package com.ztesoft.book.admin.config;

import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @Description 全局跨域放开
 * @Author YangFan
 * @Date 2021-06-22 16:53
 */
@Component
public class CorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        //HRS_REQUEST_PARAMETER_TO_HTTP_HEADER
        String origin = httpRequest.getHeader("Origin");
        if (origin != null) {
            String originHeader = urlEncoder(origin);
            httpResponse.setHeader("Access-Control-Allow-Origin", originHeader);
        }

        String method = httpRequest.getMethod();
        if (method != null) {
            String methodHeader = urlEncoder(method);
            httpResponse.setHeader("Access-Control-Allow-Methods", methodHeader);
        }

        httpResponse.setHeader("Access-Control-Max-Age", urlEncoder("3600"));

        String requestH = httpRequest.getHeader("Access-Control-Request-Headers");
        if (requestH != null) {
            String requestHeader = urlEncoder(requestH);
            httpResponse.setHeader("Access-Control-Allow-Headers", requestHeader);
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    private String urlEncoder(String header) throws UnsupportedEncodingException {
        return URLEncoder.encode(header, StandardCharsets.UTF_8.displayName());
    }

}
